<!--
 * @Descripttion: (批次追溯/cks_batch_code_data)
 * @Author: (admin)
 * @Date: (2025-09-12)
-->
<template>
    <div>
        <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
            <el-form-item :label="$t('review.cksbatchcodedataPage.page.productionLineCode')" prop="lineCode">
                <el-select clearable style="width: 260px" v-model="queryParams.productionLineCode"
                    @change="queryParams.workstationCode = ''; state.options.workstationCodeOptions = state.options.productionLineList.find(item => item.lineCode === $event)?.workStation || []"
                    :placeholder="$t('review.cksbatchcodedataPage.page.productionLineCodeInput')">
                    <el-option v-for="item in options.productionLineOptions" :key="item.dictValue"
                        :label="item.dictLabel" :value="item.dictValue" />
                </el-select>
            </el-form-item>

            <el-form-item :label="$t('review.cksbatchcodedataPage.page.stationCode')" prop="stationCode">
                <el-select clearable style="width: 260px" v-model="queryParams.workstationCode"
                    :placeholder="$t('review.cksbatchcodedataPage.page.stationCodeInput')">
                    <el-option v-for="item in options.workstationCodeOptions" :key="item.WorkstationCode"
                        :label="item.WorkstationCode" :value="item.WorkstationCode" />
                </el-select>
            </el-form-item>

            <el-form-item :label="$t('review.cksbatchcodedataPage.page.batchCode')" prop="batchCode">
                <el-input v-model="queryParams.batchCode"
                    :placeholder="$t('review.cksbatchcodedataPage.page.batchCodeInput')" clearable
                    @keyup.enter="handleQuery" style="width: 200px" />
            </el-form-item>

            <el-form-item :label="$t('review.cksbatchcodedataPage.page.createdTime')" prop="dateRange">
                <el-date-picker style="width: 360px" v-model="queryParams.dateRange" type="datetimerange"
                    :default-time="defaultTime" :shortcuts="shortcuts" value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="-" />
            </el-form-item>


            <el-form-item>
                <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
                <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
            </el-form-item>
        </el-form>
        <!-- 工具区域 -->
        <el-row :gutter="15" class="mb10">
            <el-col :span="1.5">
                <el-button type="primary" v-hasPermi="['cksbatchcodedata:add']" plain icon="plus" @click="handleAdd">
                    {{ $t('btn.add') }}
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" :disabled="single" v-hasPermi="['cksbatchcodedata:edit']" plain icon="edit"
                    @click="handleUpdate">
                    {{ $t('btn.edit') }}
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" :disabled="multiple" v-hasPermi="['cksbatchcodedata:delete']" plain
                    icon="delete" @click="handleDelete">
                    {{ $t('btn.delete') }}
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" v-hasPermi="['cksbatchcodedata:delete']" plain icon="delete"
                    @click="handleClear">
                    {{ $t('btn.clean') }}
                </el-button>
            </el-col>
            <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
        </el-row>

        <el-table :data="dataList" v-loading="loading" ref="table" border header-cell-class-name="el-table-header-cell"
            highlight-current-row @sort-change="sortChange" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />

            <el-table-column prop="id" width="80" label="ID" align="center" v-if="columns.showColumn('id')" />
            <!-- <el-table-column prop="plcId" :label="'PlcID'" align="center" v-if="columns.showColumn('plcId')" /> -->

            <el-table-column width="150" prop="productionLineCode"
                :label="$t('review.cksbatchcodedataPage.tableColumns.productionLineCode')" align="center"
                v-if="columns.showColumn('productionLineCode')" />

            <el-table-column width="150" prop="workstationCode"
                :label="$t('review.cksbatchcodedataPage.tableColumns.workstationCode')" align="center"
                v-if="columns.showColumn('workstationCode')" />

            <el-table-column width="150" prop="dbBlock" :label="$t('review.cksbatchcodedataPage.tableColumns.dbBlock')"
                align="center" v-if="columns.showColumn('dbBlock')" />

            <el-table-column prop="batchCode" :label="$t('review.cksbatchcodedataPage.tableColumns.batchCode')"
                align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('batchCode')" />

            <el-table-column width="140" prop="type" :label="$t('review.cksbatchcodedataPage.tableColumns.type')"
                align="center" v-if="columns.showColumn('type')">
                <!-- <template #default="scope">
                    <dict-tag :options="options.typeOptions" :value="scope.row.type" />
                </template> -->
            </el-table-column>

            <el-table-column width="100" prop="nullity" :label="$t('review.cksbatchcodedataPage.tableColumns.nullity')"
                align="center" v-if="columns.showColumn('nullity')">
                <template #default="scope">
                    <el-tag :type="scope.row.nullity ? 'info' : 'success'">{{ scope.row.nullity ? $t('common.yes') :
                        $t('common.no') }}</el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="createTime" :label="$t('review.cksbatchcodedataPage.tableColumns.createTime')"
                align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('createTime')" />

            <el-table-column prop="modifyTime" :label="$t('review.cksbatchcodedataPage.tableColumns.modifyTime')"
                align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('modifyTime')" />

            <el-table-column :label="$t('btn.operate')" width="200" align="center">
                <template #default="scope">
                    <el-button type="success" size="small" icon="edit" v-hasPermi="['cksbatchcodedata:edit']"
                        @click="handleUpdate(scope.row)">{{ $t("btn.edit") }}</el-button>
                    <el-button type="danger" size="small" icon="delete" v-hasPermi="['cksbatchcodedata:delete']"
                        @click="handleDelete(scope.row)">{{ $t("btn.delete") }}</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
            @pagination="getList" />


        <!-- 添加或修改批次追溯对话框 -->
        <el-dialog :title="title" :lock-scroll="false" v-model="open">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
                <el-row :gutter="20">

                    <!-- <el-col :lg="12" v-if="opertype != 1">
              <el-form-item label="Id" prop="id">
                <el-input-number v-model.number="form.id" controls-position="right" placeholder="请输入Id" :disabled="true"/>
              </el-form-item>
            </el-col>
               -->

                    <el-col :lg="12">
                        <el-form-item label="PLCID" prop="plcId">
                            <el-input v-model.number="form.plcId"
                                :placeholder="$t('review.cksbatchcodedataPage.formDialog.plcId')" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item :label="$t('review.cksbatchcodedataPage.tableColumns.dbBlock')" prop="dbBlock">
                            <el-input v-model.number="form.dbBlock"
                                :placeholder="$t('review.cksbatchcodedataPage.formDialog.dbBlock')" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item :label="$t('review.cksbatchcodedataPage.tableColumns.batchCode')"
                            prop="batchCode">
                            <el-input v-model="form.batchCode"
                                :placeholder="$t('review.cksbatchcodedataPage.formDialog.batchCode')" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item :label="$t('review.cksbatchcodedataPage.tableColumns.type')" prop="type">
                            <el-input v-model="form.type"
                                :placeholder="$t('review.cksbatchcodedataPage.formDialog.type')" />
                            <!-- <el-select v-model="form.type" placeholder="请选择产品类型">
                                <el-option v-for="item in options.typeOptions" :key="item.dictValue"
                                    :label="item.dictLabel" :value="item.dictValue"></el-option>
                            </el-select> -->
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item :label="$t('review.cksbatchcodedataPage.tableColumns.nullity')" prop="nullity">
                            <el-radio-group v-model="form.nullity">
                                <el-radio :value="true">{{ $t('common.yes') }}</el-radio>
                                <el-radio :value="false">{{ $t('common.no') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item :label="$t('review.cksbatchcodedataPage.tableColumns.createTime')"
                            prop="createTime">
                            <el-date-picker :disabled="opertype == 2" v-model="form.createTime" type="datetime"
                                :teleported="false"
                                :placeholder="$t('review.cksbatchcodedataPage.formDialog.createTime')"></el-date-picker>
                        </el-form-item>
                    </el-col>

                    <!--   
            <el-col :lg="12">
              <el-form-item label="逻辑删除" prop="isDeleted">
                <el-radio-group v-model="form.isDeleted">
                  <el-radio v-for="item in options.isDeletedOptions" :key="item.dictValue" :value="item.dictValue">
                    {{item.dictLabel}}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col> -->
                </el-row>
            </el-form>
            <template #footer v-if="opertype != 3">
                <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
                <el-button type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="cksbatchcodedata">
import { queryProductionLinePlcInfo } from '@/api/business/plcconfig.js'
import {
    listCksBatchCodeData,
    addCksBatchCodeData, delCksBatchCodeData,
    updateCksBatchCodeData, getCksBatchCodeData,
    clearCksBatchCodeData,
} from '@/api/business/cksbatchcodedata.js'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()
const today = dayjs();
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    sort: '',
    sortType: 'asc',
    productionLineCode: '',
    workstationCode: '',
    batchCode: '',
    dateRange: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')],
})
const columns = ref([
    { visible: true, prop: 'id', label: 'Id' },
    { visible: false, prop: 'plcId', label: 'PLCID' },
    { visible: true, prop: 'productionLineCode', label: '产线' },
    { visible: true, prop: 'workstationCode', label: '工站' },
    { visible: true, prop: 'dbBlock', label: '数据块' },
    { visible: true, prop: 'batchCode', label: '产品批次码' },
    { visible: true, prop: 'type', label: '产品类型' },
    { visible: true, prop: 'nullity', label: '是否禁用' },
    { visible: true, prop: 'createTime', label: '创建时间' },
    { visible: true, prop: 'modifyTime', label: '修改时间' },
    { visible: false, prop: 'isDeleted', label: '逻辑删除' },
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref();
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])
// 时间范围快捷选项
const shortcuts = [
    {
        text: proxy.$t('common.today'),
        value: () => {
            const start = new Date().setHours(0, 0, 0, 0)
            const end = new Date().setHours(23, 59, 59, 999)
            return [start, end]
        },
    },
    {
        text: proxy.$t('common.thisWeek'),
        value: () => {
            const start = new Date()
            const end = new Date().setHours(23, 59, 59, 999)
            start.setHours(0, 0, 0, 0)
            start.setDate(start.getDate() - 7)
            return [start, end]
        },
    },
    {
        text: proxy.$t('common.thisMonth'),
        value: () => {
            const start = new Date()
            const end = new Date().setHours(23, 59, 59, 999)
            start.setHours(0, 0, 0, 0)
            start.setMonth(start.getMonth() - 1)
            return [start, end]
        },
    },
    {
        text: proxy.$t('common.last3Month'),
        value: () => {
            const start = new Date()
            const end = new Date().setHours(23, 59, 59, 999)
            start.setHours(0, 0, 0, 0)
            start.setMonth(start.getMonth() - 3)
            return [start, end]
        },
    },
]

var dictParams = [
]


function getList() {
    loading.value = true;
    const formBody = JSON.parse(JSON.stringify(queryParams));
    proxy.addDateRange(formBody, queryParams.dateRange);
    delete formBody.dateRange;
    listCksBatchCodeData(formBody).then(res => {
        const { code, data } = res
        if (code == 200) {
            dataList.value = data.result
            total.value = data.totalNum
            loading.value = false
        }
    })
}

// 查询
function handleQuery() {
    queryParams.pageNum = 1
    getList()
}

// 重置查询操作
function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
}
// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1
    multiple.value = !selection.length;
}
// 自定义排序
function sortChange(column) {
    var sort = undefined
    var sortType = undefined

    if (column.prop != null && column.order != null) {
        sort = column.prop
        sortType = column.order

    }
    queryParams.sort = sort
    queryParams.sortType = sortType
    handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
    single: true,
    multiple: true,
    form: {},
    rules: {
        plcId: [{ required: true, message: proxy.$t('review.cksbatchcodedataPage.formDialogVerify.plcId'), trigger: "blur", type: "number" }],
        dbBlock: [{ required: true, message: proxy.$t('review.cksbatchcodedataPage.formDialogVerify.dbBlock'), trigger: "blur", type: "number" }],
        batchCode: [{ required: true, message: proxy.$t('review.cksbatchcodedataPage.formDialogVerify.batchCode'), trigger: "blur" }],
        type: [{ required: true, message: proxy.$t('review.cksbatchcodedataPage.formDialogVerify.type'), trigger: "change" }],
    },
    options: {
        // 产品类型 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
        typeOptions: [],
        // 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
        productionLineList: [],
        // 产线
        productionLineOptions: [],
        // workstation code
        workstationCodeOptions: [],
    }
})

const { form, rules, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel() {
    open.value = false
    reset()
}

// 重置表单
function reset() {
    form.value = {
        id: null,
        plcId: null,
        dbBlock: null,
        batchCode: null,
        type: null,
        nullity: null,
        createTime: null,
        isDeleted: null,
    };
    proxy.resetForm("formRef")
}


// 添加按钮操作
function handleAdd() {
    reset();
    open.value = true
    title.value = proxy.$t('review.cksbatchcodedataPage.formDialog.addTitle')
    form.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    opertype.value = 1
}

// 修改按钮操作
function handleUpdate(row) {
    reset()
    const id = row.id || ids.value
    getCksBatchCodeData(id).then((res) => {
        const { code, data } = res
        if (code == 200) {
            open.value = true
            title.value = proxy.$t('review.cksbatchcodedataPage.formDialog.editTitle')
            opertype.value = 2
            form.value = {
                ...data,
            }
        }
    })
}

// 添加&修改 表单提交
function submitForm() {
    proxy.$refs["formRef"].validate((valid) => {
        if (valid) {
            if (form.value.id != undefined && opertype.value === 2) {
                updateCksBatchCodeData(form.value).then((res) => {
                    proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
                    open.value = false
                    getList()
                })
            } else {
                addCksBatchCodeData(form.value).then((res) => {
                    proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
                    open.value = false
                    getList()
                })
            }
        }
    })
}

// 删除按钮操作
function handleDelete(row) {
    const Ids = row.id || ids.value

    proxy
        .$confirm(proxy.$t("common.deleteConfirm", [Ids]), proxy.$t("common.systemTips"), {
            confirmButtonText: proxy.$t('common.ok'),
            cancelButtonText: proxy.$t('common.cancel'),
            type: "warning",
        })
        .then(function () {
            return delCksBatchCodeData(Ids)
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
        })
}

// 清空
function handleClear() {
    proxy
        .$confirm(proxy.$t("common.clearConfirm"), proxy.$t("common.systemTips"), {
            confirmButtonText: proxy.$t('common.ok'),
            cancelButtonText: proxy.$t('common.cancel'),
            type: "warning",
        })
        .then(function () {
            return clearCksBatchCodeData()
        })
        .then(() => {
            handleQuery()
            proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
        })
}

queryProductionLinePlcInfo().then(res => {
    const { code, data } = res
    if (code == 200) {
        state.options.productionLineList = data;
        state.options.productionLineOptions = data.map(item => ({
            dictLabel: item.lineCode,
            dictValue: item.lineCode
        }));
    }
})

handleQuery()
</script>